package com.hanfengyi.filter;

import com.alibaba.fastjson.JSON;
import com.hanfengyi.feign.RedisFeignClient;
import com.hanfengyi.hrm.AjaxResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * User: Han
 * Date: 2020/3/4
 * Time: 21:57
 * Description:
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private RedisFeignClient redisFeignClient;

    //过滤器类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //1. 获得当前请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //2. 根据当前请求上下文获得请求对象
        HttpServletRequest request = requestContext.getRequest();
        //3. 获得请求的url路径
       if(request.getRequestURI().endsWith("/login")||request.getRequestURI().endsWith("/register"))
           return false;
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1. 获得当前请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //2. 根据当前请求上下文获得请求对象
        HttpServletRequest request = requestContext.getRequest();
        //3. 拿到请求头的token,判读如果为空或者与redis中存储的token不一致，响应错误信息！
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token))
            errorMessageResponse();

        AjaxResult tokenInRedis = redisFeignClient.get("token");
        if(!tokenInRedis.isSuccess()|| tokenInRedis.getResultObj()==null)
            errorMessageResponse();

        if(!tokenInRedis.getResultObj().toString().equals(token))
            errorMessageResponse();

        return null;
    }

    public void errorMessageResponse(){

        //1. 获得当前请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //2. 根据当前请求上下文获得响应对象
        HttpServletResponse response = requestContext.getResponse();
        requestContext.setSendZuulResponse(false); //不再响应给客户端，终止运行！
        //3. 响应页面错误信息
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(401);
        AjaxResult ajaxResult = AjaxResult.me().setSuccess(false).setMessage("没有权限的访问，请先登录！");
        try {
            response.getWriter().print(JSON.toJSONString(ajaxResult));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}